package com.tl.ip_location_relation_v4.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.dbcp2.BasicDataSource;

import com.tl.ip_location_relation_v4.entity.Ip;


public class IpLoadToDB {
	/**
	 * 
	 * @author Antg
	 * @date 2021年7月12日
	 * @param 
	 * @return
	 * @Description 将数据插入到数据库
	 */
	public static void load(List<Ip> list){
		DBPoolUtils dbPoolUtils = DBPoolUtils.getInstance();
		BasicDataSource bds = dbPoolUtils.getBasicDataSource();
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//构建sql语句
			conn = bds.getConnection();
			String sql = "insert into ip_location_data(start_ip,end_ip,location) values(?,?,?)";
			ps = conn.prepareStatement(sql);
			for(Ip ele:list){
				ps.setLong(1, ele.getStartIp());
				ps.setLong(2, ele.getEndIp());
				ps.setString(3, ele.getArea());
				ps.addBatch();
			}
			int[] result = ps.executeBatch();
			System.out.println("一共插入了"+result.length+"条数据");
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtils.release(conn, ps);
		}
	}
	
	public static void loadOneByOne(List<Ip> list){
		DBPoolUtils dbPoolUtils = DBPoolUtils.getInstance();
		BasicDataSource bds = dbPoolUtils.getBasicDataSource();
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			//构建sql语句
			conn = bds.getConnection();
			String sql = "insert into ip_location_data(start_ip,end_ip,location) values(?,?,?)";
			ps = conn.prepareStatement(sql);
			for(Ip ele:list){
				ps.setLong(1, ele.getStartIp());
				ps.setLong(2, ele.getEndIp());
				ps.setString(3, ele.getArea());
				ps.execute();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtils.release(conn, ps);
		}
	}
}
